/* Copyright (c) 2015,2016 Lucky Byte, Inc.
 */
package com.lucky_byte.pay.jar.lualib;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.lib.TwoArgFunction;
import org.luaj.vm2.lib.VarArgFunction;

import com.lucky_byte.pay.jar.WebkitPDF;

/**
 * FreeMarker 处理接口
 */
public class LuaWebkitPDF extends TwoArgFunction
{
	private static final Logger logger = LogManager.getLogger();

	@Override
	public LuaValue call(LuaValue modname, LuaValue env) {
		LuaValue library = tableOf();
		env.set("wkpdf", library);
		library.set("proc", new Processor());
		return library;
	}

	/**
	 * PDF 处理引擎
	 *
	 * 用法：proc(input_file, title, encoding, pdf_file, params)
	 */
	class Processor extends VarArgFunction
	{
		@Override
		public Varargs invoke(Varargs args) {
			String filename = args.checkjstring(1);
			File file = new File(filename);
			if (!file.exists()) {
				logger.error("文件[{}]不存在.", filename);
				return LuaValue.NIL;
			}
			if (!file.isFile()) {
				logger.error("文件[{}]不是一个常规文件.", filename);
				return LuaValue.NIL;
			}
			String title = args.checkjstring(2);
			String encoding = args.checkjstring(3);
			String pdf_file = args.checkjstring(4);
			LuaTable table = args.checktable(5);
			Map<String, String> params = new HashMap<>();
			LuaValue key = LuaValue.NIL;
			while (true) {
				Varargs n = table.next(key);
				if ((key = n.arg1()).isnil())
					break;
				LuaValue value = n.arg(2);
				params.put(key.checkjstring(), value.tojstring());
			}
			try {
				File outfile = WebkitPDF.toPDF(file, title, encoding,
						new File(pdf_file), params);
				if (outfile == null) {
					return LuaValue.NIL;
				}
				return LuaValue.valueOf(outfile.getAbsolutePath());
			} catch (IOException e) {
				logger.error("转换[{}] 到 PDF 错误[{}].",
						file.getAbsolutePath(), e.getMessage());
				return LuaValue.NIL;
			}
		}
	}

}